<template>
    <div class="table-box">
        <el-table
          ref="clientTableRef"
          :data="clientStatisticData"    
          style="width: 100%; height: 100%;"
          :header-cell-style="{ textAlign: 'center' }" 
          :cell-style="{ textAlign: 'center' }"
          :span-method="objectSpanMethod"
          v-loading="loading"
          element-loading-text="客户统计数据加载中..."
          border
        >
          <el-table-column prop="clientName" label="客户名称" width="120" />
          <el-table-column prop="clientCode" label="客户代号" width="120" />
          <el-table-column prop="sumQuantity" label="总订单量" width="110" />
          <el-table-column prop="sumWeight" label="总订货重量" width="110" />
          <el-table-column prop="totalAmount" label="总金额" width="120" />
          <el-table-column prop="completeAmount" label="完成金额" width="120" />
          <!-- <el-table-column prop="orderNum" label="订单数" width="100" /> -->
          <!-- <el-table-column prop="toBeCompltOrdNum" label="待完成订单数" width="110" /> -->
          <!-- <el-table-column prop="compltOrdNum" label="已完成订单数" width="110" /> -->
          <el-table-column label="商品明细">
            <el-table-column prop="skuName" label="商品名称" width="120" />
            <el-table-column prop="skuBrand" label="商品牌号" width="100" />
            <el-table-column prop="internalBrand" label="内部牌号" width="100" />
            <el-table-column prop="specification" label="规格型号" width="140" />
            <el-table-column prop="sumQuantitySku" label="总订单量" width="110" />
            <el-table-column prop="totalAmountSku" label="总金额" width="120" />
        </el-table-column>
        </el-table>
    </div>
    <div class="pagination-box">
        <el-pagination 
            layout="sizes, prev, pager, next" 
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, watchEffect, h, onMounted } from 'vue'
import { getStatisticClient } from '@/pages/home/views/sale/api/statistic'
import { ElMessage } from 'element-plus'
import { dragTable } from '@/pages/home/views/sale/utils/dragTable'

const props = defineProps<{
  clientName: string,
  // orderDt: string[]
}>()

const pageNum = ref(1)
const pageSize = ref(5)
const total = ref(0)
const clientStatisticData = ref([])
const loading = ref(true)
const clientTableRef = ref()

const handleCurrentChange = (val) => {
    pageNum.value = val
    getClientTableData()
}

const handleSizeChange = (val) => {
    pageSize.value = val
    getClientTableData()
}

const getClientTableData = async (orderDt?) => {
    loading.value = true
    const res = await getStatisticClient({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    orderDtFrom: orderDt?.[0] ?? "",
    orderDtTo: orderDt?.[1] ?? "",
    clientName: props.clientName ?? ""
  })
  if(!res.data.success){
    ElMessage.error(`${res.data.errorCode}: ${res.data.errorMsg}`)
    return
  }
  let clientList = []
  res.data.data.list && res.data.data.list.length > 0 && res.data.data.list.forEach((client) => {
    client.skuInfoList && client.skuInfoList.length > 0 && client.skuInfoList.forEach((sku) => {
      clientList.push({
        ...client,
        skuName: sku.skuName,
        skuBrand: sku.skuBrand,
        internalBrand: sku.internalBrand,
        specification: sku.specification,
        sumQuantitySku: sku.sumQuantitySku,
        totalAmountSku: sku.totalAmountSku
      })
    })
  })
  clientStatisticData.value = clientList
  total.value = res.data.data.total
  loading.value = false
  console.log("clientStatisticData:", res.data.data.list)
}

const objectSpanMethod = ({
  row,
  column,
  rowIndex,
  columnIndex,
}) => {
  if (["clientName","clientCode","sumQuantity","sumWeight","totalAmount","orderNum","toBeCompltOrdNum","compltOrdNum","completeAmount"].includes(column.property)) {
    if (rowIndex > 0 && clientStatisticData.value[rowIndex]["clientName"] === clientStatisticData.value[rowIndex - 1]["clientName"]) {
      return {
        rowspan: 0,
        colspan: 0,
      }
    }
    return {
      rowspan: getRowspan("clientName", rowIndex),
      colspan: 1,
    }
  }
}
const getRowspan = (key, rowIndex) => {
  let rowspan = 1;
  let curVal = clientStatisticData.value[rowIndex][key];
  for (let i = rowIndex + 1; i < clientStatisticData.value.length; i++) {
    if (clientStatisticData.value[i][key] === curVal) {
      rowspan++;
    }
    else break
  }
  return rowspan;
}

onMounted(() => {
    dragTable(clientTableRef)
})

defineExpose({
    getClientTableData
})
</script>

<style scoped>
.table-box{
    height: calc(100% - 32px);
}
.pagination-box {
    margin: 10px 0;
    display: flex;
    justify-content: flex-end;
}
.el-table {
    --el-table-header-bg-color: var(--el-bg-color-page);
    --el-table-border-color: var(--el-border-color-dark);
    --el-table-header-text-color: var(--el-text-color-primary);
}
:deep(.el-table__footer-wrapper tfoot tr td.el-table__cell){
  text-align: center;
}

</style>